#include "cgal_mesh.h"
#include "cio.h"
#include <QAction>
#include <QFileDialog>
#include <QVBoxLayout>
#include <QHBoxLayout>

CGAL_Mesh::CGAL_Mesh(QWidget *parent)
	: QMainWindow(parent)
	, mesh_(NULL)
	, glViewer_(new GLViewer)
{
	ui.setupUi(this);

	initialize();
	ConsoleInit();
}

CGAL_Mesh::~CGAL_Mesh()
{
	if (glViewer_ != NULL)
	{
		delete glViewer_;
		glViewer_ = NULL;
	}
}

void CGAL_Mesh::initialize()
{
	setWindowTitle(tr("Digital Geometry Process"));
	connect(ui.actionFileLoad_, &QAction::triggered, this, &CGAL_Mesh::loadModel);
	connect(ui.action_save_model_, &QAction::triggered, this, &CGAL_Mesh::saveModel);
	connect(ui.actionDraw_edges_status_, &QAction::triggered, this, &CGAL_Mesh::showMeshEdges);
	connect(ui.action_draw_points_status_, &QAction::triggered, this, &CGAL_Mesh::showMeshPoints);
	connect(ui.actionDraw_triangles_status, &QAction::triggered, this, &CGAL_Mesh::showMeshTriangles);
	connect(this, &CGAL_Mesh::showMesh, glViewer_, &GLViewer::setMesh);
	connect(this, &CGAL_Mesh::drawMeshByEdges, glViewer_, &GLViewer::setDrawEdgesStatus);
	connect(this, &CGAL_Mesh::drawMeshByPoints, glViewer_, &GLViewer::setDrawPointsStatus);
	connect(this, &CGAL_Mesh::drawMeshByTriangles, glViewer_, &GLViewer::setDrawTrianglesStatus);

	QVBoxLayout *layout_left_ = new QVBoxLayout;
	layout_left_->addStretch(2);

	QHBoxLayout *layout_main = new QHBoxLayout;
	layout_main->addLayout(layout_left_);
	layout_main->addWidget(glViewer_);
	layout_main->setStretch(1, 1);
	this->centralWidget()->setLayout(layout_main);

	showMaximized();
}

void CGAL_Mesh::loadModel()
{
	QString filename = QFileDialog::getOpenFileName(this, tr("Load model"), "", tr(" *.obj"));

	if (filename.isNull())
	{
		return;
	}

	if (mesh_ != NULL)
	{
		delete mesh_;
		mesh_ = NULL;
	}
	mesh_ = new CTriMesh;
	mesh_->loadMeshFrom(filename.toStdString().c_str());
	Q_EMIT showMesh(*mesh_);
}

void CGAL_Mesh::saveModel()
{
	QString filename = QFileDialog::getSaveFileName(this, "Save as...", QDir::currentPath(), "obj(*.obj)");
	if (mesh_ != NULL && mesh_->m_nVertices > 0)
	{
		mesh_->writeMeshTo(filename.toStdString().c_str());
	}
}

void CGAL_Mesh::showMeshEdges()
{
	bool checked = ui.actionDraw_edges_status_->isChecked();
	Q_EMIT drawMeshByEdges(checked);
}

void CGAL_Mesh::showMeshPoints()
{
	bool checked = ui.action_draw_points_status_->isChecked();
	Q_EMIT drawMeshByPoints(checked);
}

void CGAL_Mesh::showMeshTriangles()
{
	bool checked = ui.actionDraw_triangles_status->isChecked();
	Q_EMIT drawMeshByTriangles(checked);
}
